<template>
    <div class="login">
        <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
            <div class="title-box">
                <h3 class="title">{{ title }}</h3>
            </div>
            <el-form-item prop="username">
                <el-input v-model="loginForm.username" type="text" placeholder="用户名" size="default">
                    <template #prefix>
                        <Icon type="icon-office-user" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input
                    v-model="loginForm.password"
                    type="password"
                    placeholder="密码"
                    @keyup.enter="handleLogin"
                    show-password
                    size="default"
                >
                    <template #prefix>
                        <Icon type="icon-office-password" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item v-if="captchaEnabled" prop="code" class="code-field">
                <el-input v-model="loginForm.code" placeholder="验证码" @keyup.enter="handleLogin" size="default">
                    <template #prefix>
                        <Icon type="icon-office-code" />
                    </template>
                </el-input>
                <div class="login-code">
                    <img :src="codeUrl" @click="getCode" />
                </div>
            </el-form-item>
            <el-form-item style="width: 100%">
                <el-button
                    :loading="loading"
                    size="large"
                    type="primary"
                    style="width: 100%"
                    @click.prevent="handleLogin"
                >
                    <span v-if="!loading">登录</span>
                    <span v-else>登录中</span>
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import type { LoginData, TenantVO } from '@great/services';
import { loginService } from '@great/services';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus';
import useUserStore from '@/store/user';
import { Icon } from '@great/components';

const userStore = useUserStore();

const title = 'Garden';
const router = useRouter();

const loginForm = ref<LoginData>({
    tenantId: '000000',
    username: 'admin',
    password: 'admin123',
    code: ''
} as LoginData);

const loginRules: FormRules = {
    username: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
    password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
    code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref('/');
const loginRef = ref<FormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
    () => router.currentRoute.value,
    (newRoute: any) => {
        redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
    },
    { immediate: true }
);

const handleLogin = () => {
    loginRef.value?.validate(async (valid: boolean, fields: any) => {
        if (valid) {
            loading.value = true;
            try {
                const res = await loginService.login(loginForm.value);
                const { access_token } = res.data;
                userStore.token = access_token;
                await router.push(redirect.value || '/');
                loading.value = false;
            } catch (e) {
                loading.value = false;
                // 重新获取验证码
                if (captchaEnabled.value) {
                    await getCode();
                }
            }
        } else {
            console.log('error submit!', fields);
        }
    });
};

/**
 * 获取验证码
 */
const getCode = async () => {
    const res = await loginService.getCodeImg();
    const { data } = res;
    captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
    if (captchaEnabled.value) {
        codeUrl.value = 'data:image/gif;base64,' + data.img;
        loginForm.value.uuid = data.uuid;
    }
};

const getLoginData = () => {
    const tenantId = localStorage.getItem('tenantId');
    const username = localStorage.getItem('username');
    const password = localStorage.getItem('password');
    loginForm.value = {
        tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
        username: username === null ? String(loginForm.value.username) : username,
        password: password === null ? String(loginForm.value.password) : String(password)
    } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
    const { data } = await loginService.getTenantList();
    tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
    if (tenantEnabled.value) {
        tenantList.value = data.voList;
        if (tenantList.value != null && tenantList.value.length !== 0) {
            loginForm.value.tenantId = tenantList.value[0].tenantId;
        }
    }
};

onMounted(() => {
    getCode();
    initTenantList();
    getLoginData();
});
</script>

<style lang="scss" scoped>
.login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image: url('../assets/images/login-background.jpg');
    background-size: cover;
}

.title-box {
    display: flex;

    .title {
        margin: 0px auto 30px auto;
        text-align: center;
        color: #707070;
    }

    :deep(.lang-select--style) {
        line-height: 0;
        color: #7483a3;
    }
}

.login-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 5px 25px;
}

.login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
}

.el-login-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial, serif;
    font-size: 12px;
    letter-spacing: 1px;
}
.code-field {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-input {
        flex: 1;
        width: 0;
    }
    :deep(.el-form-item__content) {
        display: flex;
        gap: 4px;
    }
}
.login-code {
    height: 32px;
    float: right;
    border: 1px solid var(--el-border-color);
    padding: 3px;
    display: inline-flex;
    border-radius: var(--el-border-radius-base);

    img {
        cursor: pointer;
        vertical-align: middle;
        width: 70px;
        height: 100%;
    }
}
</style>
